import { _decorator, Component, director, EventMouse, EventTouch, Input, input, Node, Vec3 } from 'cc';
const { ccclass, property } = _decorator;


@ccclass('Scale')
export class Scale extends Component {
    @property(Node)
    cameraNode!: Node;

    /** 摄像机距离焦点的距离 */
    private _cameraScale: number = 1;

    /** 相机的初始位置 */
    private initPos!: Vec3;

    start() {
        this.initPos = this.cameraNode.position.clone();
    }

    onEnable() {
        input.on(Input.EventType.TOUCH_MOVE, this._onTouchMove, this)
        input.on(Input.EventType.MOUSE_WHEEL, this._onScroll, this)
    }
    onDisable() {
        input.off(Input.EventType.TOUCH_MOVE, this._onTouchMove, this);
        input.off(Input.EventType.MOUSE_WHEEL, this._onScroll, this);
    }

    private _lastTwoTouchesDistance = 0;
    private _onTouchMove(event: EventTouch) {
        let touches = event.getTouches();
        if (touches.length == 2) {
            let curDistance = touches[0].getLocation().subtract(touches[1].getLocation()).length();
            if (this._lastTwoTouchesDistance) {
                let dis = (curDistance - this._lastTwoTouchesDistance) / 500;
                if (dis != 0) {
                    dis = this._cameraScale - dis;
                    this.setCameraDis(dis)
                }
            }
            this._lastTwoTouchesDistance = curDistance;
        }

    }

    //pc端滚轮触发缩放
    private _onScroll(event: EventMouse) {
        let dis = event.getScrollY()
        dis = this._cameraScale + (dis < 0 ? 0.1 : -0.1);
        this.setCameraDis(dis);
    }

    /**设置摄像机的高度距离 */
    setCameraDis(dis: number) {
        // 缩放摄像机
        this._cameraScale = dis;
        this.cameraNode.position = this.initPos.clone().multiplyScalar(this._cameraScale)
    }
}


